<template>
  <a-modal :title="formTile + '订阅消息'" :visible="true" width="60%" :footer="null" @cancel="reset">
    <a-card>
      <a-row type="flex" justify="start" align="top">
        <a-col :span="24">
          <a-form :form="form" @submit="handleSubmit" :labelCol="formItemLayout.labelCol"
            :wrapperCol="formItemLayout.wrapperCol">
            <h3>基础信息</h3>
            <a-form-item label="标题" :required="true">
              <a-input placeholder="请输入标题" :maxLength="10" v-decorator="[
                `name`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: true,
                      whitespace: true,
                      message: '请输入标题'
                    }
                  ]
                }
              ]" />
            </a-form-item>
            <a-form-item label="海报图" :required="true" extra="750px*1440px">
              <aliossImageUpload :isMultiple="false"
                v-decorator="['img', { rules: [{ required: true, message: '请上传小程序卡片图片' }] }]"></aliossImageUpload>
            </a-form-item>
            <a-form-item label="订阅消息模板" :required="true">
              <a-select show-search placeholder="请选择订阅消息模板" optionFilterProp="children" @change="selectChange"
                @search="handleSearch" v-decorator="[
                  'template',
                  {
                    rules: [{ required: true, message: '请选择订阅消息模板!' }]
                  }
                ]">
                <a-spin v-if="loading" slot="notFoundContent" size="small" />
                <a-select-option :value="item.id" v-for="item in templates" :key="item.id">
                  {{ searchBrand(item.brandId).name + '-' + item.linkName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item :label="item.label" v-for="item in fileds" :key="item.key">
              <a-date-picker v-if="showextra(item.key)" v-decorator="[
                `${item.key}`,
                {
                  initialValue: item.val == undefined ? undefined : item.val,
                  rules: [{ required: true, message: `请选择${item.label}!` }]
                }
              ]" show-time :placeholder="`请选择${item.label}`" valueFormat="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss" />
              <a-input v-else :placeholder="`请输入${item.label}，最多20个字`" :maxLength="20" v-decorator="[
                `${item.key}`,
                {
                  validateTrigger: ['change', 'blur'],
                  initialValue: item.val || '',
                  rules: [
                    {
                      required: true,
                      whitespace: true,
                      message: `请输入${item.label}`
                    }
                  ]
                }
              ]" />
            </a-form-item>
            <a-form-item label="点击跳转路径" extra="请填写消息模板适用的小程序内页面路径，填写其他小程序路径无法跳转 路径为空，消息模板无点击跳转">
              <!-- +(\/[a-zA-Z0-9_-]+)*[^\/]$ -->
              <a-input placeholder="填写消息点击跳转路径，请保证使用 / 开头" v-decorator="[
                `weixinUrl`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      pattern: '^\/[a-zA-Z0-9_-]',
                      whitespace: true,
                      message: '请填写消息点击跳转路径，请保证使用 / 开头'
                    }
                  ]
                }
              ]" />
            </a-form-item>
            <a-form-item label="虚拟订阅人数" :required="true" extra="小程序端显示订阅人数=虚拟订阅人数+真实订阅人数">
              <a-input-number style="width:200px" placeholder="请输入虚拟订阅人数" v-decorator="[
                `baseNum`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: true,
                      message: '请输入虚拟订阅人数'
                    }
                  ]
                }
              ]" />
            </a-form-item>
            <a-form-item label="订阅成功是否跳转">
              <a-radio-group @change="JumpHandle" v-decorator="['isJump',{ initialValue:0,rules:[{required:true,message:'请选择订阅成功是否跳转'}]}]">
                <a-radio :value="0">否</a-radio>
                <a-radio :value="1">是</a-radio>
              </a-radio-group>
            </a-form-item>
            <div v-if="showJump">
              <a-form-item label="跳转引导文案">
                <a-input v-decorator="['jumptext',{rules:[{required:true,message:'请选择跳转引导文案'}]}]" :maxLength="20"
                  placeholder="填写跳转引导文案，最多20个字">
                  <a-popover slot="suffix" placement="rightTop">
                    <img slot="content" style="width:300px;height:auto" src="https://picttype1.jnby.com/message/tip.png" />
                    <a-icon type="question-circle" style="color: rgba(0,0,0,.45)" />
                  </a-popover>
                </a-input>
              </a-form-item>
              <a-form-item label="APP ID">
                <a-input v-decorator="['appid',{rules:[{required:true,message:'请填写APPID'}]}]"
                  placeholder="填写需要跳转的小程序APP ID">
                </a-input>
              </a-form-item>
              <a-form-item label="跳转路径">
                <a-input v-decorator="['jumpUrl',{
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {required:true,message:'请填写跳转路径'},
                    {
                      pattern: '^\/[a-zA-Z0-9_-]',
                      whitespace: true,
                      message: '请填写跳转路径，请保证使用 / 开头'
                    }
                  ]
                }]" placeholder="填写跳转路径，请保证使用 / 开头">
                </a-input>
              </a-form-item>
            </div>
            <h3>推送设置</h3>
            <a-form-item label="推送方式">
              <a-radio-group @change="pushTypeChange"
                v-decorator="['pushType', { initialValue: 'head', rules: [{ required: true, message: '请选择推送方式' }] }]">
                <a-radio value="head">手动推送</a-radio>
                <a-radio value="auto">自动推送</a-radio>
                <a-radio value="loop">循环推送</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="定时推送时间" v-if="pushType === 'auto'">
              <a-date-picker
                v-decorator="['notifyFixedTime', { initialValue: undefined, rules: [{ required: true, message: '请选择定时推送时间' }] }]"
                show-time format="YYYY-MM-DD HH:mm:ss" valueFormat="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
            <h3>分享设置</h3>
            <a-form-item label="小程序卡片标题">
              <a-input placeholder="请输入小程序卡片标题"
                v-decorator="['shareTitle', { rules: [{ required: true, message: '请输入小程序卡片标题' }] }]" :maxLength="20">
              </a-input>
            </a-form-item>
            <a-form-item label="小程序卡片图片" extra="500px*400px">
              <aliossImageUpload :isMultiple="false"
                v-decorator="['shareImage', { rules: [{ required: true, message: '请上传小程序卡片图片' }] }]">
              </aliossImageUpload>
            </a-form-item>
            <a-row>
              <a-col :span="16" :offset="8" class="info-action">
                <a-button type="primary" @click="reset">返回</a-button>
                <a-button type="primary" class="ml-20" html-type="submit" :loading="loading">保存</a-button>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </a-modal>
</template>

<script>
import { brands } from '../util/brand'
import moment from 'moment'
import { templateList, createMessage, templateDetail, messageDetail } from '@/api/micromall'
import JImageUpload from '../../../components/jeecg/JImageUpload'
import aliossImageUpload from '../../../components/aliossImageUpload'
import debounce from 'lodash/debounce'
import axios from 'axios'
export default {
  data() {
    return {
      current: 1,
      size: 1000,
      total: 0,
      linkName: '',
      loading: false,
      fileds: [],
      uploading: false,
      templates: [],
      formItemLayout: {
        labelCol: {
          lg:{ span:6 },
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          lg:{ span:18 },
          xl: { span: 12 },
          xs: { span: 12 },
          sm: { span: 18 }
        }
      },
      fileList: [],
      imageUrl: '',
      loading: false,
      brands,
      record: null,
      pushType: undefined,
      formTile: '新增',
      showJump:false
    }
  },
  components: { aliossImageUpload, JImageUpload },

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'message' })
  },
  props: {
    message: {
      type: Object,
      required: false,
      default: -1
    }
  },
  computed: {
    showextra() {
      return function (key) {
        return key.indexOf('date') != -1 || key.indexOf('time') != -1
      }
    }
  },
  created() {
    const { message } = this.$props
    if (message) {
      this.getMessageDetail(message)
      this.formTile = '编辑'
    }
    this.getTemplates()
  },
  methods: {
    moment,
    JumpHandle(e){
      this.showJump = e.target.value == 1
      console.log(e)
    },
    async getMessageDetail(message) {
      console.log(message)
      try {
        if (message.notifyFixedTime) {
          this.pushType = 'auto'
        }else if(message.type == 3){
          this.pushType == 'loop'
        }
        const re = await templateDetail({ id: message.linkId })
        if (re.code == 200) {
          let data = JSON.parse(message.data) //对象数组
          let templateData = re.data.templateData
          templateData = JSON.parse(templateData)
          let fileds = []
          for (const dekey in templateData) {
            fileds.push({ label: dekey, val: data[templateData[dekey]], key: templateData[dekey] })
          }
          this.fileds = fileds
        }
        if (message.img != '') {
          this.fileList = [{ url: message.img }]
        }
        this.showJump = message.isJump == 1
        let values = {
          name: message.name,
          baseNum: message.baseNum,
          img: message.img,
          template: message.linkId,
          weixinUrl: message.weixinUrl,
          pushType: message.notifyFixedTime ?  'auto' : message.type == 3 ? 'loop' :'head',
          notifyFixedTime: message.notifyFixedTime || undefined,
          shareTitle: message.shareTitle || undefined,
          shareImage: message.shareImage || undefined,
          isJump:message.isJump
        }
        console.log(message.isJump == 1,message.jumpJson != '{}')
        if(message.isJump == 1 && message.jumpJson != '{}'){
          const jumpJson = JSON.parse(message.jumpJson)
          values = Object.assign(values,jumpJson)
        }
        console.log(values)
        
        this.$nextTick(() => {
          this.form.setFieldsValue(values)
        })
      } catch (error) {
        console.log(error)
        this.$message.error(error.msg)
      }
    },
    searchBrand(weid) {
      const brand = this.brands.filter(item => item.weid == weid)
      if (brand.length > 0) {
        return brand[0]
      } else {
        return { name: '' }
      }
    },
    deleteImage(index) {
      let fileList = this.fileList
      fileList.splice(index, 1)
      this.fileList = fileList
    },
    changeupload(e) {
      this.fileList = e
    },
    selectChange(id) {
      const { templates } = this
      this.fileds = []
      const brand = templates.find(item => item.id == id)
      if (brand.templateData && brand.templateData != '') {
        const data = JSON.parse(brand.templateData)
        let fileds = []
        for (let key in data) {
          fileds.push({ label: key, val: undefined, key: data[key] })
        }
        this.fileds = fileds
      }
    },
    normFile(e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    handleSearch: debounce(function (e) {
      this.linkName = e
      this.current = 1
      this.getTemplates()
    }, 300),
    getTemplates() {
      this.loading = true
      const { current, size, linkName } = this
      console.log(current, size)
      templateList({ current, size, linkName, onlineState: 'Y' })
        .then(res => {
          if (res.code == 200) {
            this.templates = res.data.records
            this.total = res.data.total
          } else {
            this.$message.error(res.msg)
          }
          this.loading = false
        })
        .catch(err => {
          this.$message.error(err.msg)
          this.loading = false
        })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        console.log(err, values)
        if (!err) {
          this.submit(values)
        }
      })
    },
    submit(values) {
      this.loading = true
      const { fileds } = this
      const list = this.templates
      const { template: linkId, img, name,pushType, weixinUrl, baseNum, notifyFixedTime, shareTitle, shareImage,isJump,appid,jumpUrl,jumptext } = values
      let obj = {}
      fileds.forEach(item => {
        obj[item.key] = values[item.key]
      })
      const params = { linkId, isJump, img, notifyFixedTime, shareTitle, shareImage, name, weixinUrl, baseNum, data: JSON.stringify(obj) }
      if(pushType == 'loop'){
        params.type = 3
      }
      if(isJump == 1){
        params.jumpJson = JSON.stringify({appid,jumpUrl,jumptext})
      }else{
        params.jumpJson = '{}'
      }
      if (this.message) {
        params.id = this.message.id
      }
      const brand = list.find(item => item.id == linkId)
      params.brandId = brand.brandId
      params.template = brand.template
      createMessage(params)
        .then(res => {
          this.loading = false
          console.log(res)
          if (res.code == 200) {
            let text = this.messageId != -1 ? '编辑成功' : '新增成功'
            this.$message.success(text)
            this.reset()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          this.loading = false
          console.log(err)
        })
    },
    reset() {
      this.form.resetFields()
      this.loading = false
      this.fileList = []
      this.fileds = []
      this.$emit('close')
    },
    normFile(e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    pushTypeChange(e) {
      console.log(e.target.value)
      this.pushType = e.target.value
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        console.log(info)
        // Get this url from response in real world.
        this.loading = false
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },

    scollChange(e) {
      console.log('滚动事件', e)
      const { target } = e
      console.log(target.scrollTop + target.offsetHeight === target.scrollHeight, target.scrollHeight, target.scrollTop + target.offsetHeight)
      if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        console.log(target.scrollTop + target.offsetHeight === target.scrollHeight, target.scrollHeight)
        this.current++
        console.log(this.total, this.templates.length)
        if (this.total == this.templates.length) {
          return false
        }
        this.getTemplates()
      }
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}

.ml-20 {
  margin-left: 20px;
}

.poster {
  width: 100px;
  height: 100px;
  margin-right: 20px;
  position: relative;

  &:hover {
    .img-modal {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .img {
    width: 100%;
    height: 100%;
  }

  .img-modal {
    background-color: rgba(0, 0, 0, 0.5);
    display: none;
    position: absolute;
    color: #fff;
    font-size: 20px;
    width: 100%;
    top: 0;
    height: 100%;
    left: 0;
  }
}

.fileList {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
}
</style>
